//获取服务器当前时间
function getNowDate(format) {
	var time = '';
	$.ajax({
		type : "post",
		url : "/common/getNowDate",
		async : false,
		dataType : "json",
		success : function(data){
			time = toDate(data.time,format);
		},
	    error : function() {
	    	BSTYUN.dialog.warn("网络异常，请重试");
			return;
	    }
	})
	return time;
}
//点击立即购买
function buynow(id){
	var goodsId = id,
		useYear = $("#useYear").val(),
		userNum = $("#userNum").val(),
		price = $.trim($("#price").html()),
		requestURI = $("#requestURI").val(),
		loginUserRoleId = $('#loginUserRoleId').val(),
		pageNum = $('#pageNum').val();
	$.ajax({
		type : "POST",
		url : "/common/checkLogin",
		async : false,
		dataType: 'json',
		success:function(data) {
			if(data) {
				/*if(loginUserRoleId == 'ROLE_COMPANY' ){
					BSTYUN.dialog.warn("您的账户为企业账户，如果希望购买套餐，请重新注册个人用户！<br><a href='/user/registerWay' style='margin-left: 40px;color: rgb(37, 169, 216);font-size: small;'>点击这里进行注册个人用户！</a>");
					return;
				}else */
//					if(loginUserRoleId == 'ROLE_PERSON' || loginUserRoleId == 'ROLE_AGENT'){
					$.ajax({
						type:"POST",
						url:"/buy/haveRelation",
						async:false,
						data:{
							goodsId : goodsId,
							useYear : useYear,
							userNum : userNum,
							pageNum : pageNum
						},
						dataType:"json",
						success:function(data,response){
							var orderList = data.orderList;
							var goods = data.goods;
							var goodsVo = data.goodsVo;
							if(data.hasRelation){
								if(loginUserRoleId == 'ROLE_PERSON'){
									if(data.hasBuy){
										if(goodsId == orderList[0].goodsId ){
											BSTYUN.dialog.warn("您已经购买过该商品！");
										}else{
											showImmediateBuy(data,useYear,userNum,price);
										}
									}else{
										BSTYUN.dialog.warn("该商品依托于"+goods.goodsName+",请先购买"+goods.goodsName+"商品！");
									}
								//代理商用户
								}else if(loginUserRoleId == 'ROLE_AGENT'){
									if(data.hasBuy){
										showImmediateBuy(data,useYear,userNum,price);
									}else{
										BSTYUN.dialog.warn("该商品依托于"+goods.goodsName+",请先购买"+goods.goodsName+"商品！");
									}
								}else if(loginUserRoleId == 'ROLE_COMPANY'){
									if(data.hasBuy){
										if(data.isBuy ){
											BSTYUN.dialog.warn("您已经购买过该商品！");
										}else{
											showImmediateBuy(data,useYear,userNum,price);
										}
									}else{
										BSTYUN.dialog.warn("该商品依托于"+goods.goodsName+",请先购买"+goods.goodsName+"商品！");
									}
								}
								
							}else{
								if(loginUserRoleId == 'ROLE_PERSON'){
									if(data.hasBuy){
										BSTYUN.dialog.warn("您已经购买过该商品！");
									}else{
										location.href="/dredge/"+goodsId+"/"+useYear+"/"+userNum+"/0";
									}
								//代理商用户
								}else if(loginUserRoleId == 'ROLE_AGENT'){
									location.href="/dredge/"+goodsId+"/"+useYear+"/"+userNum+"/0";
								}else if(loginUserRoleId == 'ROLE_COMPANY'){
									if(data.hasBuy){
										if(data.isBuy ){
											BSTYUN.dialog.warn("您已经购买过该商品！");
										}else{
											showImmediateBuy(data,useYear,userNum,price);
										}
									}else{
										BSTYUN.dialog.warn("您的账户为企业账户，如果希望购买套餐，请重新注册个人用户！<br><a href='/user/registerWay' style='margin-left: 40px;color: rgb(37, 169, 216);font-size: small;'>点击这里进行注册个人用户！</a>");
									}
								}
							}
						}
					})
//				}
			}else {
				location.href = "/user/login?returnUrl="+requestURI;
			}
		}
	})
	
}

function addcart(id){
	var goodsId = id,
		useYear = $("#useYear").val(),
		userNum = $("#userNum").val(),
		requestURI = $("#requestURI").val(),
		loginUserRoleId = $('#loginUserRoleId').val();
	$.ajax({
		type : "POST",
		url : "/common/checkLogin",
		async : false,
		dataType: 'json',
		success:function(data) {
			if(data) {
//				if(loginUserRoleId == 'ROLE_COMPANY' ){
//					BSTYUN.dialog.warn("您的账户为企业账户，如果希望购买套餐，请重新注册个人用户！<br><a href='/user/registerWay' style='margin-left: 40px;color: rgb(37, 169, 216);font-size: small;'>点击这里进行注册个人用户！</a>");
//					return;
//				}else if(loginUserRoleId == 'ROLE_PERSON' || loginUserRoleId == 'ROLE_AGENT'){
					$.ajax({
						type:"POST",
						url:"/buy/shoppingCart/add",
						async:false,
						data:{
							goodsId : goodsId,
							useYear : useYear,
							userNum : userNum 
						},
						dataType:"json",
						success:function(data,response){
							if(data.isSuccess){
								var proname = data.goodsName,
									num = data.sumNum,
									price = data.sumPrice;
								showAddCartDialog(proname,num,price);
							}else{
								BSTYUN.dialog.warn("添加失败！请重新添加！");
							}
						}
					})
//				}
			}else {
				location.href = "/user/login?returnUrl="+requestURI;
			}
		}
	})
}

//使用人数和使用年限  下拉框选择改变价格
function changePrice(feeFormula,feeBasenum,goodsPrice){
	var useYear = $("#useYear").val(),
		userNum = $("#userNum").val();
	var price = calculateByFee(feeFormula,feeBasenum,userNum,useYear*12,goodsPrice);
	$("#price").html(price);
}


// 立即购买 弹出框
function showImmediateBuy(data,useYear,userNum,price){
	var dialog = null,
	    html = '',
	    callback = null,
	    list = data.orderList,
	    goodsVo = data.goodsVo,
	    pageUseYear = useYear,
	    pageUserNum = userNum,
	    pagePrice = price;
	
	//当前购买商品的使用年限
	var showPageUseYear = pageUseYear;
	if(showPageUseYear == 0) showPageUseYear = "20天";
	else if(showPageUseYear == -1) showPageUseYear = "∞";
	else showPageUseYear = showPageUseYear + "年";
	
	var showPageendTime;//当前购买产品截止日期
	var nowDate = new Date(getNowDate("yyyy-MM-dd"));
	if(useYear == 0) {
		showPageendTime = AddDays(nowDate,20,'day');
		showPageendTime = formatDate(showPageendTime,"yyyy-MM-dd");
	}else{
		cyear = useYear;
		showPageendTime = AddDays(nowDate,cyear,'year');
		showPageendTime = formatDate(showPageendTime,"yyyy-MM-dd");
	}
	
	html = '<div class="product_box">';
	html += '<ul class="nav_title cle"><li>订单编号</li><li>套餐名称</li><li>公司名称</li><li>域名</li><li class="special_li">子产品</li><li style="width:60px">使用年限</li><li style="width:60px">使用人数</li></ul>';

	for(var i=0;i<list.length;i++){
		//格式化订单的使用年限
		var useLife = list[i].useLife;
		if(useLife == "-1") useLife = "∞";
		
		//计算该订单的可使用的剩余时间
		var newDate = new Date(getNowDate("yyyy-MM-dd"));
		var orderOverTime = list[i].overTime,
			orderOverTime = new Date(orderOverTime),
			orderOverTime = calculateMonth(newDate,orderOverTime,'returnDate');
		var year = '',month = '',day = '';
		if(getYear(orderOverTime).year != 0) year = getYear(orderOverTime).year + '年' ;
		if(getYear(orderOverTime).month != 0) month = getYear(orderOverTime).month + '月';
		if(getYear(orderOverTime).day != 0) day = getYear(orderOverTime).day + '天';
		var overTime = year + month + day;
		
		
		//计算所购买的商品的实际能购买的最大用户数和最大使用年限和截止日期和价格
		//人数
		var dialogUserNum = pageUserNum;
		if(pageUserNum > list[i].userNum){
			dialogUserNum = list[i].userNum;
		}
		//使用年限
		var dialogUseYear = pageUseYear;//所选择年限
		var dialogPrice = 0.00;//价格
		var dialogEndTime;//
		var orderUseLife = list[i].useLife;//该订单的使用年限
		if(orderUseLife == '20天'){//商品为免费
			if(20 > getYear(orderOverTime).day){
				dialogUseYear = getYear(orderOverTime).day + '天';
				dialogPrice = 0.00;
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),getYear(orderOverTime).day,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
			}else{
				dialogUseYear = '20天';
				dialogPrice = 0.00;
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),20,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
			}
		}else if(orderUseLife == '-1'){//商品为永久
			if(dialogUseYear == '0') {
				dialogUseYear = '20天' ;
				dialogPrice = 0.00;
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),20,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
			}else if(dialogUseYear == '∞') {
				dialogUseYear = '∞' ;
				dialogPrice = pagePrice;
				dialogEndTime = '永久';
			}else {
				dialogUseYear = dialogUseYear + '年' ;
				dialogPrice = pagePrice / userNum * dialogUserNum; 
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),pageUseYear,"year");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
			}
		}else{//商品为正常
			newDate = formatDate(newDate,"yyyy-MM-dd");
			//该订单的到期时间
			var orderExcessTime = list[i].overTime;
			orderExcessTime = formatDate(new Date(orderExcessTime),"yyyy-MM-dd");
			orderExcessTime = DateDiff(newDate,orderExcessTime);
			//所选择的商品剩余时间
			var dialogExcessTime;
			if(dialogUseYear == '0') {
				dialogExcessTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),20,"day");
				dialogExcessTime = formatDate(new Date(dialogExcessTime),"yyyy-MM-dd");
				dialogExcessTime = DateDiff(newDate,dialogExcessTime);
				//比较大小
				if(dialogExcessTime < orderExcessTime)dialogExcessTime = dialogExcessTime;
				else dialogExcessTime = orderExcessTime;
				//转换成几年几月几天，界面显示
				dialogExcessTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),20,"day");
				dialogExcessTime = calculateMonth(new Date(getNowDate("yyyy-MM-dd")),dialogExcessTime,'returnDate');
				var year = '',month = '',day = '';
				if(getYear(dialogExcessTime).year != 0) year = getYear(dialogExcessTime).year + '年' ;
				if(getYear(dialogExcessTime).month != 0) month = getYear(dialogExcessTime).month + '月';
				if(getYear(dialogExcessTime).day != 0) day = getYear(dialogExcessTime).day + '天';
				dialogUseYear = year + month + day;
				//截止日期
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),getYear(dialogExcessTime).day,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
				//价格计算
				dialogPrice = 0.00;
			}else if(dialogUseYear == '∞') {
				dialogUseYear = calculateMonth(new Date(getNowDate("yyyy-MM-dd")),orderExcessTime,'returnDate');
				//转换成几年几月几天，界面显示
				var year = '',month = '',day = '';
				if(getYear(dialogUseYear).year != 0) year = getYear(dialogUseYear).year + '年' ;
				if(getYear(dialogUseYear).month != 0) month = getYear(dialogUseYear).month + '月';
				if(getYear(dialogUseYear).day != 0) day = getYear(dialogUseYear).day + '天';
				dialogUseYear = year + month + day;
				//截止日期
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),orderExcessTime,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
				//价格计算
				dialogPrice = pagePrice / userNum * dialogUserNum;
			}else {
				dialogExcessTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),dialogUseYear,"year");
				dialogExcessTime = formatDate(new Date(dialogExcessTime),"yyyy-MM-dd");
				dialogExcessTime = DateDiff(newDate,dialogExcessTime);
				//比较大小
				if(dialogExcessTime < orderExcessTime)dialogExcessTime = dialogExcessTime;
				else dialogExcessTime = orderExcessTime;
				//转换成几年几月几天，界面显示
				dialogUseYear = AddDays(new Date(getNowDate("yyyy-MM-dd")),dialogExcessTime,"day");
				var returnMonth = calculateMonth(new Date(getNowDate("yyyy-MM-dd")),dialogUseYear,'returnMonth');
				dialogUseYear = calculateMonth(new Date(getNowDate("yyyy-MM-dd")),dialogUseYear,'returnDate');
				
				var year = '',month = '',day = '';
				if(getYear(dialogUseYear).year != 0) year = getYear(dialogUseYear).year + '年' ;
				if(getYear(dialogUseYear).month != 0) month = getYear(dialogUseYear).month + '月';
				if(getYear(dialogUseYear).day != 0) day = getYear(dialogUseYear).day + '天';
				dialogUseYear = year + month + day;
				//截止日期
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),dialogExcessTime,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
				//价格计算
				dialogPrice = price / userNum / useYear / 12 * returnMonth * dialogUserNum;
			}
			
			
		}
		
		
		html += '<dl><dt class="product_inforbox"><ul class="cle">';
		html += '<li class="choose_pro"><input type="radio" name="choose_pro"></li>';
		html += '<input type="hidden"  name ="orderId" id="orderId'+list[i].orderId+'" value="'+list[i].orderId+'" />';
		html += '<input type="hidden"  name ="relationId" id="relationId'+list[i].orderId+'" value="'+list[i].goodsId+'" />';
		html += '<input type="hidden"  name ="userId" id="userId'+list[i].orderId+'" value="'+list[i].userId+'" />';
		html += '<input type="hidden"  name ="goodsNums" id="goodsNums'+list[i].orderId+'" value="'+list[i].goodsNums+'" />';
		html += '<li><span>'+list[i].orderNum+'</span></li>';
		html += '<li><span>'+list[i].goodsName+'</span></li>';
		html += '<li><span>'+list[i].belongCompanyName+'</span></li>';
		html += '<li><span>'+list[i].companyDomainName+'</span></li>';
		html += '<li class="special_li"><span>'+list[i].goodsNames+'</span></li><li style="width:60px"><span>'+useLife+'</span></li><li style="width:60px"><span>'+list[i].userNum+'</span></li>';
		html += '<li class="lookfor_detail"><a href="/consume/order/order_detail?orderId='+list[i].orderId+'" target="_blank">查看详情</a></li>';
		html += '</ul></dt>';   
		html += '<dd class="product_detail"><div><h4>您所选套餐为'+list[i].goodsName+'，最大使用人数为'+list[i].userNum+'人，截止当前时间，使用年限剩余'+overTime+'</h4>';
		html += '<dl><dt>选择该套餐后，您所购买的产品：</dt><table><tbody><tr><td></td><td>产品名称</td><td>用户数量</td><td>使用年限</td><td>截止日期</td><td>单价</td><td>原价</td></tr>';
        html += '<tr><td>当前购买</td><td>'+goodsVo.goodsName+'</td><td>'+pageUserNum+'</td><td>'+showPageUseYear+'</td><td>'+showPageendTime+'</td><td>'+goodsVo.goodsPrice+'</td><td>'+pagePrice+'</td></tr>';
        html += '<tr><td>实际购买</td><td>'+goodsVo.goodsName+'</td><td>'+dialogUserNum+'</td><td>'+dialogUseYear+'</td><td>'+dialogEndTime+'</td><td>'+goodsVo.goodsPrice+'</td><td>'+parseFloat(dialogPrice).toFixed(2)+'</td></tr></tbody></table></dl>';
		html += '<p style="color:red">确定请点击“去支付”按钮。';
		html += '<a href="javascript:void(0);" class="goto_pay" onclick="gotoPay(\''+goodsVo.goodsId+'\','+useYear+','+userNum+','+list[i].orderId+','+list[i].userId+')">去支付</a></p></div></dd>';
	}
	
	html += '<div class="page_control"><span></span></div></div>';
	dialog = BSTYUN.dialog.creat({
	  id:'gouwuche',
	  title: '',
	  content:html,
	  init:function(){
		var $content = this.DOM.content,
			$box = $content.find('.product_box'),
	        $inforbox = $box.find('.product_inforbox'),
	        $radio = $box.find('.choose_pro input'),
	        $detail = $box.find('.product_detail'),
	        $page = $box.find('.page_control span'),
	        element = 1,  //分子，当前页数,默认第一页
	        denominator = Math.ceil($inforbox.size()/3),//分母，总页数
	        page_html = '';
	    /*调整样式，使li垂直居中*/
	    
	    /*分页功能,默认显示第一条*/
	    page_html = '<span><em class="element">1</em>/<em class="denominator">'+denominator+'</em>页，共<em class="denominator">'+denominator+'</em>页，</span><span><a href="javascript:void(0);" data-flag="index">首页</a> <a href="javascript:void(0);" data-flag="prev">上一页</a> <a href="javascript:void(0);" data-flag="next">下一页</a></span>';
	    $page.html(page_html);
	    showPage(1);
	    var $ele = $page.find('.element');
	    /*绑定单选按钮事件,默认选中第一条*/
	    $radio.on('click', function(event) {
	      var $this = $(this);
	      $detail.hide();
	      $this.parents('dt').next('dd').show();
	    });
	    $radio.eq(0).trigger('click');
	    /*绑定分页按钮*/
	    $page.on('click', 'a', function(event) {
	      var $this = $(this),
	          flag = $this.attr('data-flag');
	      switch(flag){
	        case 'index':
	          $ele.text(1);
	          showPage(1);
	          break;
	        case 'next':
	          var index = parseInt($ele.text()),
	              next = null;
	          if (index < denominator) {
	            next = index+1;
	            showPage(next);
	            $ele.text(next);
	          }
	          break;
	        case 'prev':
	          var index = parseInt($ele.text()),
	              prev = null;
	          if (index > 1) {
	            prev = index-1;
	            showPage(prev);
	            $ele.text(prev);
	          }
	          break;
	      }
	    });
	    /*显示第几页*/
	    function showPage(count){// 0,1,2  3,4,5  ,6,7,8
	      var count = count,
	          range = [count*3-3,count*3-1];
	      $inforbox.each(function(index, val) {
	         var $this = $(this);
	         if (range[0] <= index && index <= range[1]) {
	           $this.show();
	         }else{
	            $this.hide().next('dd').hide();
	         }
	      });
	      /*原先选中的状态还是为选中*/
	      $radio.each(function(index, val) {
	        var $this = $(this),
	            $prarent = $this.parents('.product_inforbox'),
	            index = $inforbox.index($prarent);
	          if (range[0] <= index && index <= range[1]) {
	             if ($this.prop('checked')) {
	              $this.parents('dt').next('dd').show();
	             }
	          };
	      });
	    }
	  }
	});
	dialog.size('1045px','480px')
	dialog.position('50%','50%')//重新定位
};

//弹出框去支付   
function gotoPay(goodsId,useYear,userNum,orderId,userId){
	
	$.ajax({
		type:"POST",
		url:"/buy/checkIsContain",
		async:false,
		data:{
			goodsId:goodsId,
			orderId:orderId 
		},
		success:function(data){
			if(data.isContain){
				var newOrder = data.newOrder;
				if(newOrder.orderState == 0){
					BSTYUN.dialog.warn("您所选择的商品内已包含您即将购买的商品，如子产品中未出现您所购买的商品，请到<a href='/consume/order/manage' style='color: red;'>订单管理</a>界面进行付款完成购买操作！");
				}else{
					if(newOrder.isDredge == 0){
						BSTYUN.dialog.warn("您所选择的商品内已包含您准备购买的商品，如子产品中未出现您所购买的商品，请到<a href='/consume/order/manage' style='color: red;'>订单管理</a>界面进行开通！");
					}else{
						BSTYUN.dialog.warn("您所选择的商品内已包含您准备购买的商品，如需继续使用，请到<a href='/myservice/order/upgradeManage' style='color: red;'>我的服务</a>进行升级或者续费！");
					}
				}
			}else{
				location.href = "/buy/cartToCheck/"+goodsId+"/"+useYear+"/"+userNum+"/"+userId+"/0";
			}
		}
	})
}


//显示加入购物车弹出框
function showAddCartDialog(proname,num,price){
	var $this = $(".shopping_cart");
	var $cart = null;
	//设置购物车内容
	var cart_box = '<em>'+ proname +'</em> 已成功加入购物车<br/>购物车中有<font color="red">'+num+'</font>件商品，共计<font color="red">￥'+(parseFloat(price).toFixed(2))+'</font>';
	//设定弹出框的位置。
	var offset = $this.offset(),
		offsetx = offset.left,
		offsety = offset.top,
		resizefit = resieFit(offsetx,offsety);
	if ( $cart !== null ) {
		return false;
	};
	$cart = $.dialog({
		id: "addcart",
	    content: '加载中...',
	    left: resizefit.offsetx+'px',
	    top: resizefit.offsety+'px',
	    content: cart_box,
	    drag: false,
	    init: function(){
	    	var $title = this.DOM.titleBar;
	    	$title.find(".aui_close").on("click",function(){
	    		location.href="/mall";
	    	});
	    },
	    button:[{
	    	name: '查看购物车',
	    	callback:function(){
	    		location.href = '/buy/shoppingCart';
	    	},
	    	focus: true
	    },{
	    	name: '继续购买',
	    	callback:function(){
				location.href = '/mall';
	    	}
	    }]
	});
	//删除标题内容
	$($cart.title()).remove();
};
//微调距离tools
function resieFit(x,y){
	return {
		offsetx: x-5,
		offsety: y+32
	}
};

function getYear(str){
	var reg = /\d+/g,
		result = str.match(reg);
	return {
		year: result[0],
		month: result[1],
		day: result[2]
	}
}
